package huawei

import (
	m "multi-cloud-manage/internal/model"

	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
	ecs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2/model"
	region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2/region"
)

// 定义类（包含属性和方法）
// 属性禁止外部访问（私有）
type Provider struct {
	ak        string
	sk        string
	region    string // 区域
	projectId string
}

// 获取资源列表
func (p Provider) ListResources() (*model.ListCloudServersResponse, error) {
	// 从数据库中获取当前用户的as，ak
	ak := p.ak
	sk := p.sk

	// 创建一个认证对象
	auth := basic.NewCredentialsBuilder().
		WithAk(ak).
		WithSk(sk).
		Build()
	// 创建客户端
	client := ecs.NewEcsClient(
		ecs.EcsClientBuilder().
			WithRegion(region.ValueOf(p.region)).
			WithCredential(auth).
			Build())

	request := &model.ListCloudServersRequest{}
	response, err := client.ListCloudServers(request)
	return response, err
}

// 创建资源
func (p Provider) CreateResources(es *m.Ecs) (*model.CreatePostPaidServersResponse, error) {
	ak := p.ak
	sk := p.sk

	auth := basic.NewCredentialsBuilder().
		WithAk(ak).
		WithSk(sk).
		Build()

	client := ecs.NewEcsClient(
		ecs.EcsClientBuilder().
			WithRegion(region.ValueOf(p.region)).
			WithCredential(auth).
			Build())

	request := &model.CreatePostPaidServersRequest{}
	rootVolumeServer := &model.PostPaidServerRootVolume{
		Volumetype: model.GetPostPaidServerRootVolumeVolumetypeEnum().SSD,
	}
	var listNicsServer = []model.PostPaidServerNic{
		{
			SubnetId: es.SubnetId,
		},
	}
	serverbody := &model.PostPaidServer{
		FlavorRef:  es.FlavorRef,
		ImageRef:   es.ImageRef,
		Name:       es.Name,
		Nics:       listNicsServer,
		RootVolume: rootVolumeServer,
		Vpcid:      es.Vpcid,
	}
	request.Body = &model.CreatePostPaidServersRequestBody{
		Server: serverbody,
	}
	response, err := client.CreatePostPaidServers(request)
	return response, err
	// if err == nil {
	// 	fmt.Printf("%+v\n", response)
	// } else {
	// 	fmt.Println(err)
	// }
}

// 删除资源
func (p Provider) DeleteResources(server_id string) {

}

// 通过工厂函数，创建华为云提供商实例，
func NewProvider(ak, sk, region, projectId string) *Provider {
	return &Provider{
		ak:        ak,
		sk:        sk,
		region:    region,
		projectId: projectId,
	}
}
